<?php

// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------

namespace plugins\code_generate\model;

use think\Db;
use think\Model;

class FormModel extends Model {

    public function viewAdd($parm, $indexv, $addv, $editv, $showv) {
        //驼峰命名转下划线命名
        $catalog = $this->uncamelize($parm['controllers']);

        //生成视图
        $viewPath = "../public/themes/admin_simpleboot3/admin/$catalog/";

        //检查目录
        if (!is_dir($viewPath)) {
            mkdir($viewPath, 0777, true);
        }
        $index = $viewPath . 'index.html';
        $edit = $viewPath . 'edit.html';
        $add = $viewPath . 'add.html';
        $show = $viewPath . 'show.html';

        $indexViews = file_put_contents($index, $indexv);
        $addViews = file_put_contents($add, $addv);
        $editViews = file_put_contents($edit, $editv);
        $showViews = file_put_contents($show, $showv);
        if ($indexViews && $addViews && $editViews && $showViews) {
            return true;
        } else {
            return false;
        }
        return true;
    }

    //add方法
    public function controllerAdd($parm, $fields) {
        //生成Controller 文件
        $controllerName = ucfirst($parm['controllers']) . 'Controller.php';
        $controllerPath = "../app/admin/controller/";
        //检查目录
        if (!is_dir($controllerPath)) {
            mkdir($controllerPath, 0777, true);
        }
        $myfile = file_put_contents($controllerPath . $controllerName, $this->controller($parm, $fields));
        if ($myfile) {
            return true;
        } else {
            return false;
        }
        return true;
    }

    public function modelAdd($parm, $fields) {
        //生成model
        $modelName = ucfirst($parm['controllers']) . 'Model.php';
        $modelPath = "../app/admin/model/";
        if (!is_dir($modelPath)) {
            mkdir($modelPath, 0777, true);
        }
        $modeFile = file_put_contents($modelPath . $modelName, $this->getModel($parm, $fields, $modelName));
        if ($modeFile) {
            return true;
        } else {
            return false;
        }
        return true;
    }

    public function validateAdd($parm, $fields) {
        //生成validate
        $validatelName = ucfirst($parm['controllers']) . 'Validate.php';
        $validatelPath = "../app/admin/validate/";
        if (!is_dir($validatelPath)) {
            mkdir($validatelPath, 0777, true);
        }
        $validateFile = file_put_contents($validatelPath . $validatelName, $this->getValidate($parm, $fields, $validatelName));
        if ($validateFile) {
            return true;
        } else {
            return false;
        }
        return true;
    }

    public function getValidate($parm, $fields, $validatelName) {
        $validatelName = ucfirst($parm['controllers']) . 'Validate';
        $rule = [];
        $message = [];
        foreach ($fields as $key => $val) {
            if ($key > 0 && $val['IS_NULLABLE'] === 'NO') {
                $rule[] = "'" . $val['COLUMN_NAME'] . "' => 'require'";
            }
            if ($key > 0 && $val['IS_NULLABLE'] === 'NO') {
                $message[] = "'" . $val['COLUMN_NAME'] . ".require' => '" . $val['COLUMN_COMMENT'] . "不能为空'";
            }
        }
        $rule = implode(",", $rule);
        $message = implode(",", $message);

        $tem = '<?php
namespace app\admin\validate;

use think\Validate;

class ' . $validatelName . ' extends Validate
{
    protected $rule = [
       ' . $rule . '
    ];

    protected $message = [ 
       ' . $message . '
    ];

    protected $scene = [
        
    ];
}
        ';
        return $tem;
    }

    /**
     * @param $parm
     * @param $fields
     * @return Model|void|null
     */
    public function getModel($parm, $fields, $modelName) {
        $modelName = ucfirst($parm['controllers']) . 'Model';
        $tem = '<?php
namespace app\admin\model;

use think\Model;

class ' . $modelName . ' extends Model {
    
}';
        return $tem;
    }

    /**
      　　* 驼峰命名转下划线命名
      　　* 思路:
      　　* 小写和大写紧挨一起的地方,加上分隔符,然后全部转小写
     */
    public function uncamelize($camelCaps, $separator = '_') {
        return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
    }

    /**
     * @param $model 数据表
     */
    public function getField($model) {
        $tableName = config('database.prefix') . $model;
        $db = config('database.database');
        $sql = "select COLUMN_COMMENT,COLUMN_NAME,IS_NULLABLE from information_schema.COLUMNS where table_name = '$tableName' and table_schema = '$db'";
        //echo $sql;
        $isTable = db()->query($sql);
        return $isTable;
    }

    function controller($parm, $fields) {
        $formName = $parm['name'];
        $controllers = $parm['controllers'];
        $controllerName = ucfirst($controllers) . 'Controller';
        $sql = $parm['model'];
        $ucfirstModel = ucfirst($controllers) . 'Model';
        $hook = "admin_$controllerName";
        $modelUse = preg_replace('# #', '', 'app\admin\model' . '\ ' . $ucfirstModel);
        //菜单
        $menuParent = null;
        if (!empty($parm['category'])) {
            $result = Db::name('AdminMenu')->where("id", $parm['category'])->find();
            $menuParent = $result['app'] . '/' . $result['controller'] . '/' . $result['action'];
        }

        $tem = '<?php
namespace app\admin\controller;

use cmf\controller\AdminBaseController;
use ' . $modelUse . ';
use think\Db;
use think\db\Query;

class ' . $controllerName . ' extends AdminBaseController
{';
        if (!empty($menuParent)) {
            $tem = $tem . '
    /**
     * ' . $formName . '列表
     * @adminMenu(
     *     \'name\'   => \'' . $formName . '\',
     *     \'parent\' => \'' . $menuParent . '\',
     *     \'display\'=> true,
     *     \'hasView\'=> true,
     *     \'order\'  => 10000,
     *     \'icon\'   => \'\',
     *     \'remark\' => \'' . $formName . '列表\',
     *     \'param\'  => \'\'
     * )
     */';
        }
        $tem = $tem . '
    public function index()
    {
        $content = hook_one("' . $hook . '_index_view");
        if (!empty($content)) {
            return $content;
        }
        /**搜索条件**/
        $name = $this->request->param("name");
        $customer = Db::name("' . $sql . '")
            ->where(function (Query $query) use ($name) {
                if ($name) {
                    $query->where("name", "like", "%$name%");
                    $this->assign("name", $name);
                }
            })
            ->order("id DESC")
            ->paginate(10);
        // 获取分页显示
        $page = $customer->render();
        
        $this->assign("page", $page);
        $this->assign("data", $customer);
        return $this->fetch();
    }
    
    public function add()
    {
        $content = hook_one("' . $hook . '_add_view");
        if (!empty($content)) {
            return $content;
        }        
        return $this->fetch();
    }
    
    public function addPost()
    {
        $navModel =  new ' . $ucfirstModel . '();
        $arrData  = $this->request->post();
        $result         = $this->validate($arrData, "' . $controllers . '");
        if ($result !== true) {
            $this->error($result);
        }
        $navModel->allowField(true)->insert($arrData);
        $this->success(lang("EDIT_SUCCESS"), url("' . $controllers . '/index"));
    }
    
     public function edit()
    {
        $content = hook_one("' . $hook . '_edit_view");
        if (!empty($content)) {
            return $content;
        }        
        $id    = $this->request->param("id", 0, "intval");
        $data = DB::name("' . $sql . '")->where("id", $id)->find();
        $this->assign("vo",$data);
        return $this->fetch();
    }
    
    public function editPost()
    {
        $navModel =new ' . $ucfirstModel . '();
        $arrData  = $this->request->post();
        $result         = $this->validate($arrData, "' . $controllers . '");
        if ($result !== true) {
            $this->error($result);
        }
        $navModel->allowField(true)->isUpdate(true)->save($arrData);
        $this->success(lang("EDIT_SUCCESS"), url("' . $controllers . '/index"));
    }
    
     public function show()
    {
        $content = hook_one("' . $hook . '_show_view");
        if (!empty($content)) {
            return $content;
        }
        $id    = $this->request->param("id", 0, "intval");
        $data = DB::name("' . $sql . '")->where("id", $id)->find();
        $this->assign("vo",$data);
        return $this->fetch();
    }    
    
     public function delete()
    {
        $navModel = new ' . $ucfirstModel . '();
        $intId    = $this->request->param("id", 0, "intval");
        if (empty($intId)) {
            $this->error(lang("NO_ID"));
        }
        $navModel->where("id", $intId)->delete();
        $this->success(lang("DELETE_SUCCESS"), url("' . $controllers . '/index"));
    }    
}  
   ';
        return $tem;
    }

}
